﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace NamedPipeWrapper.IO
{
    public class PipeStreamWriterEx<T> where T : class
    {
        public PipeStream BaseStream { get; private set; }

        public PipeStreamWriterEx(PipeStream stream)
        {
            BaseStream = stream;
        }

        private byte[] Serialize(T obj)
        {
            try
            {
                var json = JsonConvert.SerializeObject(obj);
                return Encoding.UTF8.GetBytes(json);
            }
            catch
            {
                //if any exception in the serialize, it will stop named pipe wrapper, so there will ignore any exception.
                return null;
            }
        }

        private void writeObject(byte[] data)
        {
            BaseStream.Write(data, 0, data.Length);
        }

        private async Task writeObjectAsync(byte[] data)
        {
            await BaseStream.WriteAsync(data, 0, data.Length);
        }

        private void flush()
        {
            BaseStream.Flush();
        }

        private async Task flushAsync()
        {
            await BaseStream.FlushAsync();
        }

        public void WriteObject(T obj)
        {
            var data = Serialize(obj);
            writeObject(data);
            flush();
        }

        public async Task WriteObjectAsync(T obj)
        {
            var data = Serialize(obj);
            await writeObjectAsync(data);
            await flushAsync();
        }
    }
}